package com.example.mongodb.demo.service.impl;

import com.example.mongodb.demo.dao.GoodsRepository;
import com.example.mongodb.demo.model.entity.Goods;
import com.example.mongodb.demo.service.IGoodsService;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Goods findById(String id) {
        return goodsRepository.findById(id).get();
    }

    @Override
    public Goods save(Goods blog) {
        return goodsRepository.save(blog);
    }

    @Override
    public void delete(Goods blog) {
        goodsRepository.delete(blog);
    }

    @Override
    public void deleteById(String id) {
        goodsRepository.deleteById(id);
    }

    @Override
    public long update(Goods blog) {
        UpdateResult result = mongoOperations.upsert(new Query(new Criteria("id").is(blog.getId())),
                new Update().set("goodsName", blog.getGoodsName()), Goods.class);
        return result.getModifiedCount();
    }

    @Override
    public List<Goods> findByShopName(String goodsName) {
        Goods goods = new Goods();
        goods.setGoodsName(goodsName);
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<Goods> example = Example.of(goods, matcher);
        return goodsRepository.findAll(example);
    }

    @Override
    public Page<Goods> findAll(Goods blog, Pageable pageable) {
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<Goods> example = Example.of(blog, matcher);
        Sort.Order order = Sort.Order.asc("salePrice");
        Sort sort = Sort.by(order);
        PageRequest pageRequest = PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize(), sort);
        return goodsRepository.findAll(example, pageRequest);
    }
}
